//
//  BuyErrorAlert_Vc.swift
//  Pods
//
//  Created by eme on 2017/4/5.
//
//


/*
 owner:cy
 update:2017年04月05日09:28:27
 info: 弹出 购买数量不足的弹框
 */
import RxSwift
import UtilCore
import RickonCore
class BuyErrorAlert_Vc: Base_Vc {
    
    /****************************Storyboard UI设置区域****************************/
    
    @IBOutlet weak var buyError_Tv: UITableView!
    ///确定要继续结算吗？|
    @IBOutlet weak var error_type_Lb: UILabel!
    //显示的按钮区域
    @IBOutlet weak var bottom_ContentV: UIView!
    
     @IBOutlet weak var seperateLine_header_V: UIView!
    
    
    @IBOutlet weak var seperateLine_V: UIView!
    /*----------------------------   自定义属性区域    ----------------------------*/
    var createOrder:CreateOrderModel?{
        didSet{
            if let createOrder = self.createOrder {
                self.listItems = createOrder.nomai
            }
        }
    }
    var listItems = [NomaiModel](){
        didSet{
            
        }
    }
    
    var didSubmit_Closure:((_ param:String)-> Void)?
    /****************************Storyboard 绑定方法区域****************************/
    
    /// 选择地址
    /// 再想想
    lazy var thinkBtn: UIButton = {
        let button = UIButton()
        button.setTitle("再想想", for: .normal)
        button.titleLabel?.font = UIFont(name: Theme.fontName, size: 14)
        button.setTitleColor(UIColor(hex: "666666"), for: .normal)
        button.changeBorderColor(UIColor(hex: "666666"), cornerRadius: 3, borderWidth: 0.5)
        button.setBackgroundImage(UIColor.white.getImage(), for: .normal)
        return button
    }()
    /// 立即就算
    lazy var ljjsBtn: UIButton = {
        let button = UIButton()
        button.titleLabel?.font = UIFont(name: Theme.fontName, size: 14)
        button.setTitle("立即结算", for: .normal)
        button.setTitleColor(UIColor.white, for: .normal)
        button.changeBorderColor(UIColor.clear, cornerRadius: 3, borderWidth: 0.5)
        button.setBackgroundImage(Theme.btn.normal.getImage(), for: .normal)
        return button
    }()
    /// 确定
    lazy var qdBtn: UIButton = {
        let button = UIButton()
        button.titleLabel?.font = UIFont(name: Theme.fontName, size: 14)
        button.setTitle("确定", for: .normal)
        button.setTitleColor(UIColor.white, for: .normal)
        button.changeBorderColor(UIColor.clear, cornerRadius: 3, borderWidth: 0.5)
        button.setBackgroundImage(Theme.btn.normal.getImage(), for: .normal)
        return button
    }()
    
    /**************************** 以下是方法区域 ****************************/
    override func viewDidLoad() {
        super.viewDidLoad()
        
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        if let createOrder = self.createOrder  {
            self.updateBottomContentView(createOrder: createOrder)
        }
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        
    }
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        
    }
    /**
     界面基础设置
     */
    override func setupUI() {
        ///隐藏滑动条
        self.buyError_Tv.showsVerticalScrollIndicator = false
        self.buyError_Tv.estimatedRowHeight = 30
        self.buyError_Tv.rowHeight = UITableViewAutomaticDimension
        self.buyError_Tv.sectionHeaderHeight = UITableViewAutomaticDimension
        self.buyError_Tv.estimatedSectionHeaderHeight = 30
    }
    /**
     app 主题 设置
     */
    override func setViewTheme(){
        
        self.seperateLine_V.backgroundColor = Theme.v.separate_Line
        self.seperateLine_header_V.backgroundColor = Theme.v.separate_Line
        
    }
    /**
     绑定到viewmodel 设置
     */
    override func bindToViewModel(){
        
    }
}
extension BuyErrorAlert_Vc{
    func updateBottomContentView(createOrder:CreateOrderModel) -> Void {
        /// 1 表示部分商品不能购买 2是都不能购买
        if createOrder.status == "1" {
            self.error_type_Lb.text = "确定要继续提交订单吗"
            /// 需要在最后一行显示其它商品 可以正常购买一行
            self.bottom_ContentV.addSubview(self.thinkBtn)
            self.bottom_ContentV.addSubview(self.ljjsBtn)
            
            self.thinkBtn.snp.makeConstraints{ make in
                make.centerY.equalTo(self.bottom_ContentV.snp.centerY).offset(0)
                make.trailing.equalTo(self.bottom_ContentV.snp.centerX).offset(-20)
                make.width.equalTo(90)
                make.height.equalTo(35)
            }
            self.ljjsBtn.snp.makeConstraints{ make in
                make.centerY.equalTo(self.bottom_ContentV.snp.centerY).offset(0)
                make.leading.equalTo(self.bottom_ContentV.snp.centerX).offset(20)
                make.width.equalTo(90)
                make.height.equalTo(35)
            }
            self.thinkBtn
                .rx.tap
                .subscribe(onNext: { [unowned self] ( _ ) in
                    self.dismiss(animated: true, completion: nil)
                })
                .disposed(by: disposeBag)
            self.ljjsBtn
                .rx.tap
                .subscribe(onNext: { [unowned self] ( _ ) in
                    if let didSubmit_Closure = self.didSubmit_Closure{
                        if let createOrder = self.createOrder{
                            let arr = createOrder.yesmai.map({ (item) -> [String : AnyObject ] in
                                item.dictionaryRepresentation()
                            })
                            didSubmit_Closure(JSONHelper.parseToJson(arr as AnyObject) as String)
                            self.dismiss(animated: true, completion: nil)
                        }
                    }
                })
                .disposed(by: disposeBag)
            
        }else{
            self.error_type_Lb.text = "可重新下单哦！"
            self.bottom_ContentV.addSubview(self.qdBtn)
            self.qdBtn.snp.makeConstraints{ make in
                make.centerY.equalTo(self.bottom_ContentV.snp.centerY).offset(0)
                make.centerX.equalTo(self.bottom_ContentV.snp.centerX).offset(0)
                make.width.equalTo(90)
                make.height.equalTo(35)
            }
            self.qdBtn
                .rx.tap
                .subscribe(onNext: { [unowned self] ( _ ) in
                    self.dismiss(animated: true, completion: nil)
                })
                .disposed(by: disposeBag)
        }
        
        
    }
}

// MARK: UITableViewDelegate
extension BuyErrorAlert_Vc :UITableViewDataSource{
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
        if section < self.listItems.count {
            let model = self.listItems[section]
            return model.productSpecsnap.count
        }else{
            // 表示应该只有 status为1 即 加了一个section 显示 其它商品 可以正常购买一行
            return 1
        }
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{
        let cell = tableView.dequeueReusableCell(withIdentifier: "BuyErrorAlert_TCell", for: indexPath) as! BuyErrorAlert_TCell
        if indexPath.section < self.listItems.count {
            let item = self.listItems[indexPath.section].productSpecsnap[indexPath.row]
            cell.title_Lb.text = "\(item.psvalue) \(item.mes)"
        }else{
            cell.title_Lb.text = "其他商品可正常购买"
        }
        if UIDevice.current.systemVersion.hasSuffix("8") {
            cell.setNeedsUpdateConstraints()
            cell.updateConstraintsIfNeeded()
        }
        return cell
    }
    func numberOfSections(in tableView: UITableView) -> Int {
        if let createorder = self.createOrder {
            /// 1 表示部分商品不能购买 2是都不能购买
            if createorder.status == "1" {
                /// 需要在最后一行显示其它商品 可以正常购买一行
                return self.listItems.count + 1
            }else if createorder.status == "2" {
                return self.listItems.count
            }
        }
        return 0
    }
    
}
// MARK: UITableViewDelegate
extension BuyErrorAlert_Vc: UITableViewDelegate {
    /// 点击行事件
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath){
        
    }
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat{
        if self.createOrder!.status == "1" {
            /// 需要在最后一行显示其它商品 可以正常购买一行
            if section == self.listItems.count {
                return 0
            }
            
        }else if self.createOrder!.status == "2" {
            if section == self.listItems.count - 1 {
                return 0
            }
        }
        return 6
    }
    ///自定义view
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        if section < self.listItems.count {
            let cell = self.buyError_Tv.dequeueReusableCell(withIdentifier: "BuyErrorAlert_TCell") as! BuyErrorAlert_TCell
            let item = self.listItems[section]
            cell.title_Lb.text = "\(item.pdname):"
            if UIDevice.current.systemVersion.hasSuffix("8") {
                cell.setNeedsUpdateConstraints()
                cell.updateConstraintsIfNeeded()
            }
            return cell
        }
        return nil
    }
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView?{
        if self.createOrder!.status == "1" {
            /// 需要在最后一行显示其它商品 可以正常购买一行
            if section == self.listItems.count {
                return nil
            }
            
        }else if self.createOrder!.status == "2" {
            if section == self.listItems.count - 1 {
                return nil
            }
        }
        let cell = self.buyError_Tv.dequeueReusableCell(withIdentifier: "erroralertfootercell")
        return cell
    }
    
}
